<template>
  <div>
    <group>
      <cell
        :title="title"
        @click.native="onClickOrg"
        :value="selectedPersonsOrg"
      ></cell>
    </group>
    <div v-transfer-dom>
      <popup v-model="showOrg" :height="height">
        <popup-header
          left-text="清除已选"
          right-text="确定"
          title=""
          :show-bottom-border="false"
          @on-click-left="clickLeftOrg"
          @on-click-right="clickRightOrg"
        ></popup-header>
        <tab>
          <tab-item selected @on-item-click="onTabClick">组织机构</tab-item>
          <tab-item @on-item-click="onTabClick">最近</tab-item>
        </tab>
        <div v-show="tab === 0">
          <!-- 组织机构回退导航 -->
          <div ref="bar" class="org-bar" v-show="selectedOrg.length > 0">
            <ul ref="barul">
              <li
                v-for="org in selectedOrg"
                :key="org.orgId"
                @click="orgBack(org)"
              >
                {{ org.orgName }}
              </li>
            </ul>
          </div>
          <!-- 组织机构 -->
          <group class="myGroup" v-if="orgList.length > 0">
            <cell
              :title="org.orgName"
              v-for="org in orgList"
              :key="org.ordId"
              @click.native="clickOrg(org)"
              is-link
            ></cell>
          </group>
          <!-- 组织机构下的人员 -->
          <checklist
            title=""
            :max="max"
            :check-disabled="false"
            :options="personList"
            v-model="selectedPerson"
            @on-change="changeOrgPerson"
          ></checklist>
          <div class="getMoreOrNot">没有更多人员</div>
        </div>
        <div v-show="tab === 1">
          <checklist
            title=""
            :max="max"
            :options="recentPerson"
            v-model="selectedPersonRecent"
            @on-change="changeOrgPersonRecent"
          ></checklist>
          <div class="getMoreOrNot" v-if="recentPerson.length === 0">
            没有记录
          </div>
          <div class="getMoreOrNot" v-else @click="showClearLocal = true">
            清除本地记录
          </div>
        </div>
        <!-- 清本地缓存 -->
        <div v-transfer-dom>
          <confirm
            v-model="showClearLocal"
            title=""
            @on-cancel="showClearLocal = false"
            @on-confirm="clearLocalByUser"
          >
            <p style="text-align: center">是否删除本地缓存？</p>
          </confirm>
        </div>
        <!-- 清除已选 -->
        <div v-transfer-dom>
          <confirm
            v-model="showClearSelected"
            title=""
            @on-cancel="showClearSelected = false"
            @on-confirm="clearSelected"
          >
            <p style="text-align: center">是否清空已选？</p>
          </confirm>
        </div>
      </popup>
    </div>
  </div>
</template>

<script>
import {
  Tab,
  TabItem,
  XHeader,
  Group,
  Cell,
  CellBox,
  Radio,
  XSwitch,
  TransferDom,
  Popup,
  XButton,
  PopupHeader,
  Checklist,
  Confirm,
} from "vux";
import BScroll from "better-scroll";
const LOCAL_KEY = "__current_person__";
export default {
  directives: {
    TransferDom,
  },
  components: {
    Tab,
    TabItem,
    XHeader,
    Group,
    Cell,
    CellBox,
    Radio,
    XSwitch,
    Popup,
    XButton,
    PopupHeader,
    Checklist,
    Confirm,
  },
  props: {
    title: {
      type: String, // cell的title
      default: "处理人",
    },
    height:{
      type: String, // popup 高度
      default: "90%",
    },
    maxName: {
      type: Number, // 最大显示几个名字？默认2
      default: 2,
    },
    max: {
      // 支持多选和单选 单选=1，多选大于1
      type: Number,
      default: 10000,
    },
    expiredDays: {
      // “最近”数据最多保留多少天 <=0 不限制
      type: Number,
      default: 30,
    },
  },
  data() {
    return {
      orgCitic: {
        orgId: "1",
        orgName: "中信总行",
        subOrg: [
          {
            orgId: "11",
            orgName: "北京市分行",
            subOrg: [
              {
                orgId: "111",
                orgName: "西城支行",
                staff: [
                  {
                    key: "1090",
                    value: "麻槐德0",
                  },
                  {
                    key: "1091",
                    value: "麻槐德1",
                  },
                  {
                    key: "1092",
                    value: "麻槐德2",
                  },
                  {
                    key: "1093",
                    value: "麻槐德3",
                  },
                  {
                    key: "1094",
                    value: "麻槐德4",
                  },
                  {
                    key: "1095",
                    value: "麻槐德5",
                  },
                  {
                    key: "1096",
                    value: "麻槐德6",
                  },
                  {
                    key: "1097",
                    value: "麻槐德7",
                  },

                  {
                    key: "1098",
                    value: "麻槐德8",
                  },
                  {
                    key: "1099",
                    value: "麻槐德9",
                  },
                  {
                    key: "1190",
                    value: "麻槐德10",
                  },
                  {
                    key: "1191",
                    value: "麻槐德11",
                  },
                  {
                    key: "1192",
                    value: "麻槐德12",
                  },
                ],
                subOrg: [
                  {
                    orgId: "1111",
                    orgName: "广安门营业厅",
                    subOrg: [
                      {
                        orgId: "345666",
                        orgName: "红莲南里MINI营业厅",
                        staff: [
                          {
                            key: "91100",
                            value: "王天龙1",
                          },
                          {
                            key: "91101",
                            value: "王天龙2",
                          },
                          {
                            key: "91102",
                            value: "王天龙3",
                          },
                          {
                            key: "91103",
                            value: "王天龙4",
                          },
                        ],
                      },
                    ],
                    staff: [
                      {
                        key: "1100",
                        value: "赵恒晨0",
                      },
                      {
                        key: "1101",
                        value: "赵恒晨1",
                      },
                      {
                        key: "1102",
                        value: "赵恒晨2",
                      },
                      {
                        key: "1103",
                        value: "赵恒晨3",
                      },
                      {
                        key: "1104",
                        value: "赵恒晨4",
                      },
                      {
                        key: "1105",
                        value: "赵恒晨5",
                      },
                      {
                        key: "1106",
                        value: "赵恒晨6",
                      },
                      {
                        key: "1107",
                        value: "赵恒晨7",
                      },

                      {
                        key: "1108",
                        value: "赵恒晨8",
                      },
                      {
                        key: "1109",
                        value: "赵恒晨9",
                      },
                      {
                        key: "1110",
                        value: "赵恒晨10",
                      },
                      {
                        key: "1111",
                        value: "赵恒晨11",
                      },
                    ],
                  },
                  {
                    orgId: "1112",
                    orgName: "长椿街营业厅",
                  },
                  {
                    orgId: "1113",
                    orgName: "宣武门营业厅",
                  },
                ],
              },
              {
                orgId: "112",
                orgName: "东城支行",
              },
              {
                orgId: "113",
                orgName: "朝阳支行",
              },
              {
                orgId: "114",
                orgName: "海淀支行",
              },
              {
                orgId: "115",
                orgName: "石景山支行",
              },
              {
                orgId: "116",
                orgName: "通州支行",
              },
            ],
          },
          {
            orgId: "12",
            orgName: "天津市分行",
          },
          {
            orgId: "13",
            orgName: "上海市分行",
          },
          {
            orgId: "14",
            orgName: "重庆市分行",
          },
          {
            orgId: "15",
            orgName: "深圳市分行",
          },
          {
            orgId: "16",
            orgName: "广州市分行",
          },
        ],
      },
      showOrg: false,
      personList: [], // 待选人员列表
      orgList: [], // 待选组织机构
      selectedPerson: [], // 已选人员列表
      selectedOrg: [], // 已选组织机构，导航bar
      selectedOrgPerson: new Map(), // 已选的组织机构和人
      betterScroller: null,
      tab: 0,
      recentPerson: [], // "最近"备选
      selectedPersonRecent: [], // “最近”已选
      showClearLocal: false, //是否删除本地缓存提示
      showClearSelected: false, //是否删除已选提示
    };
  },
  computed: {
    // 已选人员中文名称，怕显示不下，最多只显示前俩名字
    selectedPersonsOrg() {
      if (this.selectedPerson.length == 0) {
        return "请选择";
      } else {
        let names = [];
        this.selectedPerson.forEach((item) => {
          names.push(this.selectedOrgPerson.get(item).label);
        });
        if (names.length > this.maxName) {
          return names.slice(0, this.maxName).join(",") + "...";
        } else {
          return names.join(",");
        }
      }
    },
  },
  watch: {
    selectedOrg(n, o) {
      if (n.length > 0) {
        this.orgBarScrollX();
      }
    },
    showOrg(n, o) {
      if (!n) {
        this.submit();
      }
    },
  },
  methods: {
    //tab切换
    onTabClick(index) {
      this.tab = index;
    },
    // 清除已选人员提示
    clickLeftOrg() {
      if (this.selectedPerson.length > 0) {
        this.showClearSelected = true;
      }
    },

    // 清除已选
    clearSelected() {
      this.selectedPerson = [];
      this.selectedOrgPerson = new Map();
      this.selectedPersonRecent = [];
    },

    // 开启popup
    onClickOrg() {
      this.showOrg = true;
      this.orgList = [
        {
          orgId: this.orgCitic.orgId,
          orgName: this.orgCitic.orgName,
        },
      ];
      this.personList = JSON.parse(JSON.stringify(this.orgCitic.staff || []));
      this.selectedOrg = [];
      // 从localstorage里面取得“最近”
      this.getLocalstorage();
    },

    // 确定
    clickRightOrg() {
      this.showOrg = false;
    },

    /**
     * 选择人员，由于翻页导致的备选人员列表被清空，需要在此组织每个org下面选择的人
     * emit时记录到localstorage，再次点开后，用此数据当做“最近”页面备选
       (111:{org:[{orgId:1,orgName:"总行"},{orgId:11,orgName:"分行"},{orgId:111,orgName:"支行"}],label:"张三"})
     * 
     */
    changeOrgPerson(value, label) {
      value.forEach((item, index) => {
        // 只有当前页的才记录
        if (item !== label[index]) {
          this.selectedOrgPerson.set(item, {
            org: JSON.parse(JSON.stringify(this.selectedOrg)),
            label: label[index],
            currentTime: new Date().getTime(),
          });
        }
        // 如果在“最近”中的备选里面有
        let isInRecent = this.recentPerson.find((rp) => rp.key == item);
        // 如果在“最近”中的已选里面没有
        let isInRecentSelected = this.selectedPersonRecent.indexOf(item);
        if (isInRecent && isInRecentSelected == -1) {
          // 备选需要增加
          this.selectedPersonRecent.push(item);
        }
      });
      // 如果“最近”备选中有，但是组织机构中已经删除了，且“最近”已选中有，需要删除
      this.recentPerson.forEach((rp) => {
        let key = rp.key;
        let indexOrg = this.selectedPerson.indexOf(key);
        let indexRecent = this.selectedPersonRecent.indexOf(key);
        if (indexOrg == -1 && indexRecent != -1) {
          this.selectedPersonRecent.splice(indexRecent, 1);
        }
      });
    },

    // “最近”人员列表选择
    changeOrgPersonRecent(value, label) {
      value.forEach((item, index) => {
        if (this.recentPerson.find((obj) => obj.key === item)) {
          let org = this.recentPerson.find((obj) => obj.key === item).org;
          this.selectedOrgPerson.set(item, {
            org: JSON.parse(JSON.stringify(org)),
            label: label[index],
            currentTime: new Date().getTime(),
          });
        }

        // 如果“最近”中选择了，还得同步组织机构中已选的
        if (this.selectedPerson.indexOf(item) == -1) {
          this.selectedPerson.push(item);
        }
      });
      // 如果“最近”中未选的，组织机构已选了，需要删除
      this.recentPerson.forEach((rp) => {
        let indexOrg = this.selectedPerson.indexOf(rp.key);
        let indexRecent = this.selectedPersonRecent.indexOf(rp.key);
        if (indexOrg != -1 && indexRecent == -1) {
          this.selectedPerson.splice(indexOrg, 1);
        }
      });
    },

    // 根据orgId 查询subOrg/staff
    querySubOrgStaffByOrgId(orgId, orgCitic) {
      if (!orgCitic || orgCitic.length === 0) {
        return;
      }
      if (orgId == this.orgCitic.orgId) {
        this.orgList = this.orgCitic.subOrg || [];
        this.personList = this.orgCitic.staff || [];
      } else {
        orgCitic.forEach((org) => {
          if (org.orgId == orgId) {
            this.orgList = org.subOrg || [];
            this.personList = org.staff || [];
          } else {
            // 递归往下查
            this.querySubOrgStaffByOrgId(
              orgId,
              JSON.parse(JSON.stringify(org.subOrg || []))
            );
          }
        });
      }
    },

    // 点击了组织机构
    clickOrg(org) {
      this.querySubOrgStaffByOrgId(
        org.orgId,
        JSON.parse(JSON.stringify(this.orgCitic.subOrg))
      );
      this.selectedOrg.push({
        orgId: org.orgId,
        orgName: org.orgName,
      });
    },

    // 点击组织机构导航bar回退
    orgBack(org) {
      if (this.selectedOrg.length == 0) {
        return;
      }
      let orgIndex = 0;
      // 找到点的是哪一个
      this.selectedOrg.forEach((item, index) => {
        if (item.orgId === org.orgId) {
          orgIndex = index;
        }
      });
      // 如果是第一个就不管了
      if (orgIndex === this.selectedOrg.length - 1) {
        return;
      } else {
        // 组织机构bar裁剪
        this.selectedOrg = this.selectedOrg.slice(0, orgIndex);
        this.clickOrg(org);
      }
    },

    // 让组织机构bar滚起来
    orgBarScrollX() {
      this.$nextTick(() => {
        if (!this.betterScroller) {
          this.betterScroller = new BScroll(this.$refs.bar, {
            startX: 0,
            click: true,
            scrollX: true,
            scrollY: false,
            eventPassthrough: "vertical",
            click: true,
            bounce: {
              top: false,
              bottom: false,
              left: true,
              right: true,
            },
          });
        } else {
          this.betterScroller.refresh();
        }
        // 当选中的组织机构UL长度大于bar时，需要向右滚动差值
        let barWidth = parseFloat(getComputedStyle(this.$refs.bar).width);
        let ulWidth = parseFloat(getComputedStyle(this.$refs.barul).width);
        if (ulWidth > barWidth) {
          this.betterScroller.scrollTo(-(ulWidth - barWidth), 0, 400);
        }
      });
    },

    // 向父组件提交
    submit() {
      // 已选人员ID
      this.$emit(
        "getSelectedValue",
        JSON.parse(JSON.stringify(this.selectedPerson))
      );
      let realOrgPerson = new Map();
      if (this.selectedPerson.length > 0) {
        this.selectedPerson.forEach((item) => {
          realOrgPerson.set(item, this.selectedOrgPerson.get(item));
        });
      }
      // 已选人员ID对应的组织机构和名称
      this.$emit("getSelectedOrg", realOrgPerson);
      // 把已选人员存储到本地local中
      this.saveLocalstorage(realOrgPerson);
      console.log("pserson", this.selectedPerson);
      console.log("org", realOrgPerson);
    },

    // 把已选人员存储到本地local中
    saveLocalstorage(realOrgPerson) {
      let localPserson = "";
      let local = window.localStorage.getItem(LOCAL_KEY);
      if (local && local != "undefined") {
        localPserson = new Map(
          JSON.parse(window.localStorage.getItem(LOCAL_KEY))
        );
        // 如果本地有了，看看是否过期
        localPserson = this.clearLocal(localPserson);
        for (let key of realOrgPerson.keys()) {
          localPserson.set(key, realOrgPerson.get(key));
        }
        window.localStorage.setItem(LOCAL_KEY, JSON.stringify(localPserson));
      } else {
        window.localStorage.setItem(LOCAL_KEY, JSON.stringify(realOrgPerson));
      }
    },

    // 从localstorage里面取得“最近”
    getLocalstorage() {
      let localPserson = "";
      let local = window.localStorage.getItem(LOCAL_KEY);
      if (local && local != "undefined") {
        localPserson = new Map(
          JSON.parse(window.localStorage.getItem(LOCAL_KEY))
        );
        this.recentPerson = [];
        for (let key of localPserson.keys()) {
          let inlineDesc = [];
          localPserson.get(key).org.forEach((item) => {
            inlineDesc.push(item.orgName);
          });
          this.recentPerson.push({
            key,
            value: localPserson.get(key).label,
            inlineDesc: inlineDesc.join("/"),
            oldTime: localPserson.get(key).currentTime,
            org: localPserson.get(key).org,
          });
          this.recentPerson.sort((a, b) => {
            return b.oldTime - a.oldTime;
          });
          // 如果组织机构里面有了，“最近”备选中也有，但是“最近”已选中没有，需要增加
          if (this.selectedPerson.length > 0 && this.recentPerson.length > 0) {
            this.selectedPerson.forEach((item) => {
              let isInRecent = this.recentPerson.find((rp) => rp.key === item);
              let isInRecentSelected = this.selectedPersonRecent.indexOf(item);
              if (isInRecent && isInRecentSelected == -1) {
                this.selectedPersonRecent.push(item);
              }
            });
          }
        }
      }
    },

    // 清理过期的local
    clearLocal(map) {
      if (this.expiredDays <= 0) {
        return map;
      } else {
        for (let key of map.keys()) {
          let oldTime = map.get(key).currentTime;
          let now = new Date().getTime();
          let millTime = this.expiredDays * 24 * 3600 * 1000;
          if (now - oldTime > millTime) {
            map.delete(key);
          }
        }
        return map;
      }
    },

    // 用户直接清除本地
    clearLocalByUser() {
      window.localStorage.clear(LOCAL_KEY);
      this.recentPerson = [];
    },
  },
  destroyed() {
    this.betterScroller && this.betterScroller.destroy();
  },
};
</script>

<style lang="less" scoped>
.myGroup {
  /deep/ .weui-cells {
    margin-top: 0;
  }
}
.getMoreOrNot {
  width: 100%;
  height: 3.2rem;
  line-height: 3.2rem;
  text-align: center;
  color: #ddd;
  background-color: #fff;
}
/deep/.vux-popup-header-left {
  color: #04be02;
}
/deep/.vux-popup-dialog {
  background-color: #fff;
}
.org-bar {
  width: 100%;
  height: 2.3rem;
  line-height: 2.3rem;
  font-size: 1rem;
  color: #04be02;
  overflow: hidden;
  > ul {
    display: inline-block;
    width: auto;
    box-sizing: border-box;
    padding: 0 0 0 14px;
    white-space: nowrap;
    > li {
      display: inline-block;
      margin: 0 5px 0 0px;
      &:not(:first-child):before {
        display: inline-block;
        content: "/";
      }
      &:last-child:not(:first-child) {
        color: rgba(0, 0, 0, 0.5);
      }
    }
  }
}
</style>